<template>
	<div class="app-container relative">
		<el-form :model="data.info" :label-width="language == 'en' ? '150px' : '100px'" class="w-1/2" ref="ruleFormRef">
			<el-form-item :label="$t('machine.custom.pushTitle') + ':'" prop="adv_title">
				<el-input v-model="data.info.adv_title" :placeholder="$t('message.pleaseEnter')" />
			</el-form-item>

			<el-form-item :label="$t('advment.info.adMaterials') + ':'" prop="res_id">
				<el-select v-model="data.info.res_id" :placeholder="$t('message.pleaseSelect')" clearable filterable
					@change="onadvtitle">
					<el-option v-for="item in data.advlist.filter(e => {
						switch (data.info.push_type) {
							case 1:
								return e.type === 1 || e.type === 2
							case 2:
								return e.type === 1
							case 3:
								return e.type === 3
							default:
								return true
						}
					})" :key="item.res_id" :label="item.res_id + '-' + item.title" :value="item.res_id" />
				</el-select>
			</el-form-item>

			<el-form-item :label="$t('machine.custom.material') + ':'" prop="file_path" v-if="data.material != ''">
				<div v-if="data.material.type == 1" class="flex justify-center">
					<el-image class="max-w-40 max-h-40" :src="data.material.file_path" fit="fill" />
				</div>
				<div v-if="data.material.type == 2" class="max-w-40">
					<Video :url="data.material.file_path" :control="false" />
				</div>
				<div v-if="data.material.type == 3" class="max-w-40">
					<audio :src="data.material.file_path" controls controlsList="nodownload" />
				</div>
			</el-form-item>

			<el-form-item :label="$t('advment.info.pushType') + ':'" prop="push_type">
				<el-select v-model="data.info.push_type" :placeholder="$t('message.pleaseSelect')" @change="changeType"
					filterable>
					<el-option v-for="item in typeList" :label="$t(item.label)" :value="item.value" />
				</el-select>
			</el-form-item>

			<el-form-item :label="$t('machine.custom.placement') + ':'" prop="position">
				<el-select v-model="data.info.position" :placeholder="$t('message.pleaseSelect')" filterable>
					<el-option v-for="item in data.positionList" :label="$t(item.label)" :value="item.value" />
				</el-select>
			</el-form-item>

			<el-form-item :label="$t('machine.custom.screenPosition') + ':'" prop="screen" v-if="false">
				<el-select v-model="data.info.screen" :placeholder="$t('message.pleaseSelect')">
					<el-option :label="$t('machine.custom.home')" :value="1" />
					<el-option :label="$t('machine.custom.second')" :value="2" />
				</el-select>
			</el-form-item>
			<!-- 是否全屏 -->
			<el-form-item :label="$t('machine.custom.advertisePosition') + ':'" prop="screen_full" v-if="false">
				<el-select v-model="data.info.screen_full" :placeholder="$t('message.pleaseSelect')">
					<!-- 是 -->
					<el-option :label="$t('machine.custom.fullScreen')" :value="1" />
					<!-- 否 -->
					<el-option :label="$t('machine.custom.homeAds')" :value="2" />
				</el-select>
			</el-form-item>

			<el-form-item :label="$t('machine.custom.placement') + ':'" prop="position" v-if="false">
				<el-select v-model="data.info.position" :placeholder="$t('message.pleaseSelect')" filterable>
					<el-option v-for="item in data.advposition" :label="item.label" :value="item.value" />
				</el-select>
			</el-form-item>

			<el-form-item v-if="data.material.type == 1" :label="$t('advment.info.duration') + ':'"
				prop="duration_time">
				<el-input v-model="data.info.duration_time" :placeholder="$t('message.pleaseEnter')" />
			</el-form-item>

			<el-form-item :label="$t('advment.info.totalNum') + ':'" prop="total_times" v-if="data.material.type != 3">
				<el-input v-model="data.info.total_times" :placeholder="$t('message.pleaseEnter')" />
			</el-form-item>

			<el-form-item :label="$t('machine.marketing.Applicable') + ':'" prop="grouping" v-if="!data.machine_status"
				v-prmis="'machine_group_mg_getList'">

				<el-cascader :placeholder="$t('message.selectGroup')" style="width:40%;margin-right: 1%;" clearable
					:props="propss" v-model="data.groupValue" @change="getmping($event, 1)" @visible-change="onVisibleChange"/>

				<el-select v-model="data.macping" :placeholder="$t('message.pleaseMachine')" clearable filterable
					style="width:40%;" @change="getmping($event, 2)">
					<el-option v-for="item in data.maclist" :key="item.m_id"
						:label="item.machine_id + '-' + item.machine_name" :value="item.machine_id" />
				</el-select>

				<div class="w-full dashed mt-2 p-2" v-if="data.grouping.length != 0">
					<el-tag v-for="item, key of data.grouping" :key="key" closable :disable-transitions="false"
						class="mr-2" :type="item.mg_id == undefined ? '' : 'warning'" size="large"
						@close="handleClose(key)">
						{{ item.machine_id || '' }}{{ item.mg_name || item.label ||' - ' + item.machine_name }}
					</el-tag>
				</div>

			</el-form-item>

			<el-form-item :label="$t('date.releaseDate') + ':'" prop="timearr">
				<el-date-picker v-model="data.timearr" :disabled-date="disabledDate" type="daterange"
					:range-separator="$t('public.to')" :start-placeholder="$t('date.startDate')"
					:end-placeholder="$t('date.endDate')" value-format="YYYY-MM-DD" :shortcuts="shortcuts"
					:editable="false" />
			</el-form-item>

			<el-form-item :label="$t('date.playTime')" prop="timelist">
				<el-time-picker v-model="data.info.timelist" is-range :range-separator="$t('public.to')"
					:start-placeholder="$t('date.startTimes')" :end-placeholder="$t('date.endTimes')"
					value-format='HH:mm:ss' :clearable="false" />
			</el-form-item>

			<div class="w-full text-center">
				<div class="inline-block">

					<el-button size="small" type="primary" @click="submit()">
						{{ $t('public.save') }}
					</el-button>

					<el-button size="small" @click="cancell">
						{{ $t('public.cancel') }}
					</el-button>

				</div>
			</div>

		</el-form>
		<div class="absolute top-0 right-0 w-1/2 pt-6 pl-20 " v-if="data.info.push_type == 2">
			<div class="w-64 h-96 bg-[#fadbd8] p-2 "
				v-if="data.info.position == 1 || data.info.position == 2 || data.info.position == 3">
				<div class=" h-6 bg-[#f5aca5] "></div>
				<div class=" h-32 bg-[#d0d0d0] mt-2 flex items-stretch">
					<span class="self-center px-20 font-bold">980px*600px</span>
				</div>
			</div>
			<div class="w-64 h-96 bg-[#d2eefa] p-2"
				v-if="data.info.position == 7 || data.info.position == 9">
				<div class=" h-6 bg-[#96d7f7] "></div>
				<div class=" h-32 bg-[#d0d0d0] mt-2 flex items-stretch">
					<span class="self-center px-20 font-bold">980px*600px</span>
				</div>
			</div>
			<div class="w-64 h-96 bg-[#d2eefa] p-2 relative" v-if="data.info.position == 8 ">
				<div class=" h-6 bg-[#96d7f7] "></div>
				<div class="w-60 h-32 bg-[#d0d0d0] flex items-stretch absolute bottom-6">
					<span class="self-center px-20 font-bold">980px*600px</span>
				</div>
			</div>
		</div>
	</div>
</template>

<script lang="ts" setup>
import { useI18n } from 'vue-i18n'
const { t: $t, locale } = useI18n()
import Video from '@/components/Video/index.vue';
import level from '@/utils/level';
import { getmachineList } from '@/api/machine';
import { getgroupList, getListgroupmg } from "@/api/machine_type";
import { getresourceList, addpush } from '@/api/machine_custom';
import { useRouter, useRoute } from "vue-router";
import { onMounted } from 'vue'
let language = ref()
let router = useRouter()
const route = useRoute()
let typeList = ref([])
onMounted(() => {
	language.value = locale.value
})

let changeType = (value: number) => {
	let arr = typeList.value.filter(item => {
		return item.value == value
	})
	data.positionList = arr[0].list
}

let shortcuts = [
	{
		text: '最近七天',
		value: () => {
			const start = new Date();
			const end = new Date();

			start.setTime(start.getTime() + 3600 * 1000 * 24 * 7);
			return [end, start];
		}
	},
	{
		text: '最近三十天',
		value: () => {
			const start = new Date();
			const end = new Date();

			start.setTime(start.getTime() + 3600 * 1000 * 24 * 30);
			return [end, start];
		}
	},
	{
		text: '最近三个月',
		value: () => {
			const start = new Date();
			const end = new Date();
			start.setTime(start.getTime() + 3600 * 1000 * 24 * 90);
			return [end, start];
		}
	}
];

let data = reactive({
	groupValue:[],
	nodesData:[],
	machine_status: false, // 是否默认选中设备
	advlist: [], // 素材列表信息
	maclist: [], // 设备列表信息
	timearr: [], // 投放日期
	advposition: [], // 投放位置
	macgrouping: [], // 设备分组
	bindmacping: [], // 设备分组绑定的设备
	grouping: [], // 展示分组/设备
	macping: '', // 选中的分组/设备

	original: '', // 原始数据
	material: '', // 素材信息
	info: { // 主体信息
		push_type: 2,
		adv_title: '',
		res_id: '',
		duration_time: '0',
		total_times: '0',
		m_id: [],
		start_date: '',
		end_date: '',
		timelist: ['00:00:00', '23:59:59'],
		screen: 1,
		screen_full: 1,
		position: 1
	},
	typeList: [],
	positionList: []
})
const propss = reactive(
	{
		checkStrictly: true,
		lazy: true,
		multiple: false,
		async lazyLoad(node: any, resolve: any) {
			const { level, value } = node
			let nodes = await getgroupList({ pid: value });
			if (nodes.state == 100 || nodes.state == 300) {
				resolve([]);
			}
			const nodesa = nodes.data.map((item) => ({
				value: item.mg_id,
				label: item.mg_id + '-' + item.mg_name
			}))
			nodes.data.forEach(item => {
				data.nodesData.push({
					value: item.mg_id,
					label: item.mg_id + '-' + item.mg_name
				})
			})
			resolve(nodesa);
		}
	}
)

// 获取接口信息
let geturlinfo = async () => {
	if (route.query.l != undefined) {
		data.machine_status = true
		let id = JSON.parse(decodeURI(route.query.l)).info
		data.grouping = [{ m_id: id }]
	}

	data.original = JSON.stringify(data.info)

	// 获取投放位置
	data.advposition = level.getadvpos(1)
	let arr = level.positionList.filter(item => {
		return item.push_type == 2 || item.push_type == 3
	})
	typeList.value = arr
	level.positionList.forEach(item => {
		if (item.value == 2) {
			data.positionList = item.list
		}
	})

	// 获取素材列表
	data.advlist = []

	await getresourceList().then(res => {
		if (res.state == 200) {
			for (let item of res.data) {
				if (item.status == 1) {
					data.advlist.push(item)
				}
			}
		}
	})

	// 获取设备列表
	await getmachineList().then(res => {
		if (res.state == 200) {
			data.maclist = res.data
		}
	})

	// 获取设备分组
	await getgroupList().then(res => {
		if (res.state == 200) {
			data.macgrouping = res.data
		}
	})

	// 获取分组中的设备
	await getListgroupmg().then(res => {
		if (res.state == 200) {
			data.bindmacping = res.data
		}
	})

}

// 选中素材
let onadvtitle = (e) => {
	data.material = ''
	setTimeout(() => {
		for (let item of data.advlist) {
			if (item.res_id == e) {
				data.material = item
			}
		}
	}, 10)
}

// 日期选择
let disabledDate = (time: Date) => {
	return time.getTime() < Date.now() - 3600 * 1000 * 24 * 1
}
let onVisibleChange = () =>{
	data.groupValue = []
}
// 选中分组/设备
let getmping = (e, k) => {
	let obj = ''
	let status = true
	if (k == 1) {
		// 分组
		data.nodesData.map((item) => {
			if (item.value === e[e.length - 1]) obj = item
		})
		for (let item of data.grouping) {
			if (item.value == obj.value) {
				status = false
			}
		}
	} else {
		// 设备
		data.maclist.map((item) => { if (item.machine_id === e) obj = item })
		for (let item of data.grouping) {
			if (item.m_id == obj.m_id) {
				status = false
			}
		}
		data.macping = ''
	}
	if (status) {
		data.grouping.push(obj)
	}
	
}

// 删除选中的设备分组/设备
let handleClose = (e) => {
	data.grouping.splice(e, 1)
}

// 保存
let submit = () => {
	let machine = []

	if (data.info.adv_title == '' || data.info.res_id == '' || data.info.time == '') {
		ElMessage({
			message: $t('message.pleaseFill'),
			type: 'error'
		});
		return;
	}

	if (data.info.screen_full == 2 && data.material.type == 2) {
		ElMessage({
			message: $t('message.onlyAllowsAdv'),
			type: 'error'
		});
		return
	}

	if (data.grouping.length == 0) {
		ElMessage({
			message: $t('message.pleaseSelectMachine'),
			type: 'error'
		})
		return
	}

	if (data.grouping.length != 0) {
		let grouping = []
		for (let item of data.grouping) {
		// 设备
			if (item.mg_id != undefined) {
				data.bindmacping.map((ime) => {
					if (item.mg_id === ime.mg_id) {
						grouping.push(ime.m_id)
					}
				})
			}

			if (item.m_id != undefined) {
				grouping.push(item.m_id)
			}
			// 设备分组
			if (item.value != undefined) {
				data.bindmacping.map((ime) => {
					if (item.value === ime.mg_id) {
						if(ime.m_id !== undefined){
							grouping.push(ime.m_id)
						}	
					}
				})
			}
		}
		// 设备分组放入指定设备中
		machine = [...machine, ...grouping]
	}

	// 去除重复的设备编号
	machine = [...new Set(machine)]

	if (data.timearr.length == 0) {
		ElMessage({
			message: $t('message.pleaseSelectDate'),
			type: 'error'
		})
		return
	}

	let adv = {
		adv_title: data.info.adv_title,
		res_id: data.info.res_id,
		duration_time: data.info.duration_time,
		total_times: data.info.total_times,
		m_id: machine.join(','),
		start_date: data.timearr[0],
		end_date: data.timearr[1],
		time_list: data.info.timelist[0] + '~' + data.info.timelist[1],
		screen: data.info.screen,
		screen_full: data.info.screen_full,
		push_type: data.info.push_type,
		position: data.info.position
	};

	addpush(adv).then(res => {
		if (res.state == 200) {
			ElMessage({
				message: $t('message.pushSuccess'),
				type: 'success'
			});
			router.back()
			return;
		}
		ElMessage({
			message: $t('message.networkFailed'),
			type: 'error'
		});
	});
}

// 取消
let cancell = () => {
	data.info = JSON.parse(data.original)
	data.material = ''
	router.back()
}

geturlinfo()

</script>
<style type="text/css">
.dashed {
	border: 2px dashed var(--el-border-color);
}
</style>